﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using PPIDesktopClient.General;
using VMind.Global;
using PPIDesktopClient.Entities.Kml;
using PPIProxy;
using PPIDesktopClient.Entities;

namespace PPIDesktopClient.Logic
{
    public class LSettings
    {
        public static List<EKmlFile> SelectKML()
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            DataTable _Dt = WSettings.SelectKml(_Reader.GetConnectionString()).Tables[0];
            List<EKmlFile> _KmlCodes = new List<EKmlFile>();

            foreach (DataRow dr in _Dt.Rows)
            {
                EKmlFile _Kml = new EKmlFile();
                _Kml.KMLCode = ParseKml(ConvertHelper.Tostring(dr["Value"]));
                _KmlCodes.Add(_Kml);
            }
            return _KmlCodes;
        }
        private static string ParseKml(string databaseKml)
        {
            string returnKml = "";
            try
            {
                int _StartingIndex = databaseKml.IndexOf("<Document>") + "<Document>".Length;
                returnKml = databaseKml.Substring(_StartingIndex, databaseKml.Length - _StartingIndex);
                _StartingIndex = returnKml.IndexOf("</Document>");
                returnKml = returnKml.Substring(0, _StartingIndex);
                return returnKml;
            }
            catch (Exception ex)
            {
                 returnKml = "Invalid KML";
                 return returnKml;
            }
        }
        public static void Update(int id, string text)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            WSettings.Update(id, text,_Reader.GetConnectionString());
        }

        public static EBaseSettings SelectByKey(EBaseSettings settingBase)
        {
            ConfigReader _Reader = ConfigReader.GetInstance();
            EBaseSettings _ReturnSettings = (EBaseSettings)settingBase.Clone();
            
            DataTable _dt = WSettings.SelectByKey(settingBase.Key,_Reader.GetConnectionString()).Tables[0];

            if (_dt.Rows.Count > 0)
            {
                _ReturnSettings.Id = ConvertHelper.ToInt32(_dt.Rows[0]["SettingId"]);
                _ReturnSettings.Text = ConvertHelper.Tostring(_dt.Rows[0]["SettingText"]);
                _ReturnSettings.Value = ConvertHelper.Tostring(_dt.Rows[0]["SettingValue"]);            
            }
            return _ReturnSettings;
       
        }
    }
}
